package com.mischa.atc;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/*
 * Represents a radar screen
 */
public class RadarScreen {
	List<Flight> _flights;

	// private Timer _timer;
	// private UpdateTimerTask _updateTask;
	//
	// private static int sweepAroundTime = 2000;
	// private static int sweepSectorWidth = 5;

	Controller _controller;
	RadarScreenDrawer _drawer;
	Heading _heading = new Heading();

	// Width and height in nm
	private int _size;

	public RadarScreen(Controller controller, RadarScreenDrawer drawer) {
		_controller = controller;
		_drawer = drawer;

		_flights = new ArrayList<Flight>();
	}


	public void setDisplayRangeInNM(int sizeInNM) {
		_size = sizeInNM;
	}
	
	public int getDisplayRangeInNM()
	{
		return _size;
	}

	public void sweep(int sectorWidth, float timeStepInSeconds) {
		_heading.add(sectorWidth);
		
		if (_drawer != null) {
			_drawer.sweeping((int)Math.rint(_heading.get()));
		}

		Iterator<Flight> flightIterator = _controller.getIterator();

		while (flightIterator.hasNext()) {
			Flight flight = flightIterator.next();

			Heading positionOfFlightWrtOrigin = flight.getPosition().headingFromOrigin();
 
			if(positionOfFlightWrtOrigin.liesBetweenCW(_heading.get(), _heading.get() + sectorWidth)) 
			{
				flight.update(timeStepInSeconds);

				// Note: the positive y-axis has negative y-coordinate, hence the +/-
				// If getX() is 0 then x will be 0.5
				// If getX() is +/- _size then x will be 0 or 1
				float x = (float) (flight.getPosition().getX() / _size);
				float y = (float) (flight.getPosition().getY() / _size);

				// if (Math.abs(flight.getPosition().getX()) > _width || 
				//	Math.abs(flight.getPosition().getY()) > _height)
				if(flight.getPosition().distanceFromOrigin() > _size)
				{				
					if (_drawer != null)
						_drawer.flightOutOfRange(flight);
					// Note: must remove flight through iterator to prevent
					// ConcurrentModificationException
					flightIterator.remove();
				}
				else 
				{
					if (_drawer != null)
						_drawer.DrawFlight(flight, x, y);
				}
			}
		}
	}
	
	
}
